package io.renren.modules.thirdpartyverification.controller;

import cn.hutool.core.util.CharsetUtil;
import io.renren.common.utils.AesUtil;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisKeys;
import io.renren.common.utils.RedisUtils;
import io.renren.modules.gasstation.gasstationenterprise.service.GasStationEnterpriseService;
import io.renren.modules.thirdpartyverification.controller.constant.OrdinaryConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;

/**
 * @Author：T-weiwei
 * @Description: 三方验证接口
 * @Email：tweiwei@aliyun.com
 * @CreateDate：2022-01-11-上午9:51
 * @CopyRight：http://www.huaxun.ink/
 * @Hint： This content is limited to the internal circulation of HuaXun Hi Tech Co., Ltd.,
 * and is forbidden to be leaked and used for other commercial purposes
 **/
@RestController
@RequestMapping("/thirdpartyverification/verification")
public class VerificationController {

    /**
     * 加油站企业业务类
     */
    @Autowired
    private GasStationEnterpriseService enterpriseService;

    /**
     * redis工具类
     */
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 根据加密的企业社会信用代码推送token
     * @param content 加密后的社会信用代码
     * @return 是否成功标识
     */
    @GetMapping("/getToken")
    public R getUserToken(@RequestParam("content") String content) {
        String decryptedContent = "";
        try {
            // 解密传输过来的社会信用代码
//            decryptedContent = AesUtil.getInstance().decryptStrFromBase64(content, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception e){
            return R.ok().put("code", OrdinaryConstant.FALSE).put("msg", OrdinaryConstant.FAILURE_REMINDER);
        }

        // 更具社会信用代码查询该企业是否存在
        Boolean isExistEnterprise = this.enterpriseService.isExistEnterpriseByEnterpriseCode(decryptedContent);
        if (isExistEnterprise) {
            // 如果存在该企业，需要给用户返回token
            String token = this.redisUtils.get(RedisKeys.GAS_STATION_ENTERPRISE_PREFIX + decryptedContent);
            // 如果token过期，需要重新获取token并发送
            if (StringUtils.isEmpty(token)) {
                String newToken = UUID.randomUUID().toString().replace("-", "");
                this.redisUtils.set(RedisKeys.GAS_STATION_ENTERPRISE_PREFIX + decryptedContent, newToken, OrdinaryConstant.THIRTY_DAY);
                return R.ok().put("token", newToken);
            } else {
                // 如果token没有过期则直接返回
                return R.ok().put("token", token);
            }

        } else {
            return R.ok().put("code", OrdinaryConstant.FALSE);
        }
    }

}
